from flask import Blueprint, request, make_response, jsonify, redirect
import json, random, time, requests, functools
from application.models.users.user import *
from db import db
from flask_restful import reqparse
from tools.Myredis import r
from tools.comm import get_ali_object
goods_blue = Blueprint("goodsblue", __name__)


@goods_blue.route("/addcart",methods=['POST'])
def addcart():
    data = reqparse.RequestParser()
    data.add_argument("userid")
    data.add_argument("cid")
    args = data.parse_args()
    userid = int(args["userid"])
    cid = int(args["cid"])
    if not all([userid,cid]):
        return jsonify({'code':400,'msg':'数据不存在'})

    cart = Cart.query.filter(Cart.cid == cid).first()
    if cart:
        sql = "update cart set count=count+1 where cart.cid=%d" % (cid)
        db.add(sql)
        db.commit()
        return jsonify({"code": 200, "msg": "加入购物车成功"})
    else:
        count = 1
        sql1 = "insert into cart(userid,cid,count) values('%d','%d','%d')" % (userid,cid,count)
        # sql = Cart(userid=userid,cid=cid,count=count)
        db.add(sql1)
        db.commit()
        return jsonify({"code":200,"msg":"加入购物车成功"})


# 我的购物车
# @goods_blue.route("/getshop")
# def getshop():
#     req = reqparse.RequestParser()
#     req.add_argument('userid')
#     args = req.parse_args()
#     list = []
#     sql = "select * from cart where cart.userid=%d"%int(args['userid'])
#     res = db.findAll(sql)
#     print('1111',res)
#     for i in res:
#         sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
#         res1 = db.findAll(sql1)
#         for j in res1:
#             list.append({
#                 'id':j['id'],
#                 'title':j['title'],
#                 'price':j['price'],
#                 'count':i['count'],
#                 'url':j['url'],
#                 'amount':(j['price'] * i['count'])
#             })
#     return jsonify({'code':200,'msg':'ok','data':list})

@goods_blue.route("/gettcourse")
def getcart():
    userid = request.args.get("userid")
    cartlist = []
    tmoney = 0
    cid = 0
    sql = "select * from cart where cart.userid=%d"% int(userid)
    res = db.findAll(sql)
    for i in res:
        sql = "select * from course where course.id=%d"%int(i['cid'])
        res = db.findAll(sql)
        print(res)
        for j in res:
            d ={
                "id":j["id"],
                "title":j["name"],
                "price":j["tcount"],
                "url":j["url"],
                "count":i["count"],
                "amount":(j["tcount"] * i["count"])
            }
            cartlist.append(d)
            tmoney = j["tcount"] * i["count"]
            cid = i['cid']
    return jsonify({"code": 200, "msg":"ok","cartlist": cartlist,"tmoney":tmoney,"cid":cid})


# 购物车数量加
@goods_blue.route('/addcount',methods=["POST"])
def Add_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()
    print(args['id'], 12222222222)

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.findAll(sql)
    print(res, 8888888)
    for i in res:
        sql1 = "update Cart set count=count+1 where cart.userid=%d and cart.cid=%d" % (
        int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code': 200, 'msg': '加成功'})


# 购物车数量减
@goods_blue.route('/mincount',methods=["POST"])
def Min_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()
    print(args['id'], 12222222222)

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.findAll(sql)
    print(res, 8888888)
    for i in res:
        sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (
        int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code': 200, 'msg': '减成功'})


# 删除购物车数据
@goods_blue.route('/delcount', methods=["POST"])
def delcount():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = db.findAll(sql)
    for i in res:
        sql1 = "delete from Cart where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        db.add(sql1)
        db.commit()
    return jsonify({'code':200,'msg':'ok'})



from tools.comm import get_ali_object
# 调用支付宝  进行购买
# @goods_blue.route('/zfshop', methods=["POST"])
# def zfshop():
#     req = reqparse.RequestParser()
#     req.add_argument('userid')
#     args = req.parse_args()
#     money = 200
#     tmoney = money * int(10)
#     order_no = str(int(time.time())) + str(args['userid']) + str(random.randint(100,999))
#     # 支付页面 支付
#     pay = get_ali_object()
#     query_params = pay.direct_pay(
#         subject='购物车订单',  # 商品简单描述
#         out_trade_no=str(order_no),  # 用户购买的商品订单号（每次不一样） 20180301073422891
#         total_amount=tmoney,  # 交易金额(单位: 元 保留俩位小数)
#     )
#     pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
#     return jsonify({
#         'code': 200,
#         'url': pay_url
#     })
#
#
# #  支付宝回调接口
# @goods_blue.route('/callback')
# def callback():
#     return redirect('http://localhost:8080/#/cart')



# 提交订单
from tools.comm import get_ali_object
@goods_blue.route("/zfshop",methods=["POST"])
def zfshop():
    data=json.loads(request.data)
    userid=int(data["userid"])
    tmoney=int(data["tmoney"])
    cid=int(data["cid"])
    sum=0
    sql = "select * from cart where userid=%d" % userid
    res=db.findAll(sql)
    if not res:
        return jsonify({"code":500,"msg":"没有该商品"})
    sum+=float(tmoney)
    print(sum)
    # 订单号
    number = int(str(userid) + str(random.randint(1000, 9999)))
    create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    status = 2
    try:
        usql = vipuser_course(courseid=cid,userid=userid)
        db.add(usql)
        isql = Orders(create_time=create_time,update_time=update_time,userid=userid,courseid=cid,number=number,tmoney=sum,status=status,price=sum)
        db.add(isql)
        sqlcart = Cart.query.filter(Cart.userid==userid).first()
        sqlcart = "delete from cart where userid=%d"% int(userid)
        db.add(sqlcart)
        db.commit()
    except:
        db.rollback()
    # 支付
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买课程",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })



@goods_blue.route("/callback")
def callback():
    data = request.args
    datames = {k: v for k, v in data.items()}
    # 删除字典中key为sign的记录
    sign = datames.pop('sign')
    # 鉴权
    pay = get_ali_object()
    flag = pay.verify(datames, sign)
    print(flag)
    if flag == True:
        # 订单号
        order_no = datames["out_trade_no"]
        # 事务处理
        try:
            # 订单号更新订单表
            print(order_no)
            record = Orders.query.filter(Orders.number == order_no).first()
            record.status = 3
            db.session.add(record)
            db.session.commit()
        except:
            db.session.rollback()
    else:
        print("鉴权失败")
    #跳转到个人中心
    return redirect('http://localhost:8080/#/')

